package com.example.service.impl;

import ch.qos.logback.classic.Logger;
import com.example.entity.authority.SysRoleAuthor;
import com.example.entity.authority.SysUserRole;
import com.example.entity.authority.SystemRole;
import com.example.ext.entity.ExtSystemRole;
import com.example.mapp.SysRoleAuthorMapp;
import com.example.mapp.SysUserRoleMapp;
import com.example.mapp.SystemRoleMapp;
import com.example.service.SystemRoleService;
import com.example.util.ResultUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by youkun on 2017/9/4.
 */
@Service
public class SystemRoleServiceImpl implements SystemRoleService{

    private final static Logger logger = (Logger) LoggerFactory.getLogger(SystemRoleServiceImpl.class);


    @Autowired
    private SystemRoleMapp systemRoleMapp;

    @Autowired
    private SysRoleAuthorMapp sysRoleAuthorMapp;

    @Autowired
    private SysUserRoleMapp sysUserRoleMapp;
    /**
     * 查询列表
     * @param systemRole
     * @return
     */
    @Override
    public Map<String,Object> queryList(ExtSystemRole systemRole) {
        List<SystemRole> list =null;
        Map<String,Object> map = new HashMap<String,Object>();
        try {
            Page<SystemRole> page = PageHelper.startPage(systemRole.getCurrentPage(), systemRole.getPageSize());
            list = systemRoleMapp.queryList(systemRole);
            map.put("list",list);
            map.put("total",page.getTotal());

        } catch (Exception e) {
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("成功",map);
    }

    @Override
    public Map<String,Object> queryListAll(ExtSystemRole c) {
        List<SystemRole> list =null;
        try {
            list = systemRoleMapp.queryList(c);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("成功",list);
    }

    /**
     * 根据角色类型查询角色
     * @param roleTypeId
     * @return
     */
    @Override
    public Map<String, Object> queryByRoleTypeId(String roleTypeId) {
        List<SystemRole> list =null;
        try {
            list = systemRoleMapp.queryByRoleTypeId(roleTypeId);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("成功",list);
    }

    /**
     * 查询机构类型下的所有角色
     * @param partyType
     * @return
     */
    @Override
    public Map<String, Object> queryByPartyTypeList(String partyType) {
        List<SystemRole> list =null;
        try {
            list = systemRoleMapp.queryByRoleTypeId(partyType);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("成功",list);
    }

    /**
     * 添加
     * @param systemRole
     * @return
     */
    @Override
    @Transactional
    public Map<String,Object> add(ExtSystemRole systemRole) {
        try {
            SystemRole s = systemRoleMapp.queryByName(systemRole);
            if(null!=s){
                throw  new Exception(systemRole.getRoleName()+"已存在!");
            }
            //添加角色
            systemRole.setUseState("1");
            systemRoleMapp.add(systemRole);
            //添加角色和功能的关系
            for(int i=0;i<systemRole.getList().size();i++) {
                SysRoleAuthor sysRoleAuthor = new SysRoleAuthor();
                sysRoleAuthor.setAuthorId(Integer.parseInt(systemRole.getList().get(i).toString()));
                sysRoleAuthor.setRoleId(Integer.parseInt(systemRole.getId().toString()));
                sysRoleAuthorMapp.add(sysRoleAuthor);
            }
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("成功",null);
    }

    /**
     * 更新
     * @param systemRole
     * @return
     */
    @Override
    @Transactional
    public Map<String,Object> update(ExtSystemRole systemRole) {
        try {
            SystemRole s = systemRoleMapp.queryById(systemRole.getId().toString());
            if(null==s){
                throw  new Exception("数据不存在！");
            }
            if(!s.getRoleName().equals(systemRole.getRoleName())){
                SystemRole ss = systemRoleMapp.queryByName(systemRole);
                if(null!=ss){
                    throw  new Exception(systemRole.getRoleName()+"已存在!");
                }
            }
            systemRoleMapp.update(systemRole);
            //更新角色和权限的关系
            //1.删除角色和权限的关系
            sysRoleAuthorMapp.deleteSysRoleAuthorByRoleId(systemRole.getId().toString());
            //2.添加角色和权限的关系
            for(int i=0;i<systemRole.getList().size();i++) {
                SysRoleAuthor sysRoleAuthor = new SysRoleAuthor();
                sysRoleAuthor.setAuthorId(Integer.parseInt(systemRole.getList().get(i).toString()));
                sysRoleAuthor.setRoleId(Integer.parseInt(systemRole.getId().toString()));
                sysRoleAuthorMapp.add(sysRoleAuthor);
            }
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("成功",null);
    }

    /**
     * 删除
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public Map<String,Object> deleteById(List<String> ids) {
        try {
            for(int i=0;i<ids.size();i++){
                systemRoleMapp.deleteSystemRoleById(ids.get(i));
                sysRoleAuthorMapp.deleteSysRoleAuthorByRoleId(ids.get(i));
            }
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error(e.getMessage());
            return ResultUtil.returnError("失败"+e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("成功",null);
    }

    /**
     * 查询一条的信息
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> queryById(String id) {
        SystemRole systemRole =null;
        try {
            systemRole = systemRoleMapp.queryById(id);
        }catch (Exception e){
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("成功",systemRole);
    }

    /**
     * 查询机构下的角色
     * @param owenOrgId
     * @return
     */
    @Override
    public Map<String, Object> findByOwnerOrgList(String owenOrgId) {
        List<SystemRole> systemRoleList =null;
        try {
          //  systemRoleList = systemRoleMapp.findByOwnerOrgList(owenOrgId);
        }catch (Exception e){
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("成功",systemRoleList);
    }

    /**
     * 查询拥有用户的角色
     * @param userId
     * @return
     */
    @Override
    public Map<String, Object> findListByUserId(String userId) {
        List<SysUserRole> sysUserRoles =null;
        try {
            //sysUserRoles = sysUserRoleMapp.findListByUserId(userId);
        }catch (Exception e){
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("成功",sysUserRoles);
    }
}
